import Vue from 'vue'
import VueRouter from 'vue-router'
// 导入相关组件
import Login from '../components/Login'
import Home from '../components/Home'
import Welcome from '../components/Welcome'
import Users from '../components/users/Users'
Vue.use(VueRouter)
const router = new VueRouter({
  routes: [
    { path: '/', redirect: '/login' },
    { path: '/login', component: Login },
    {
      path: '/home',
      component: Home,
      redirect: '/welcome',
      children: [
        { path: '/welcome', component: Welcome },
        { path: '/users', component: Users }
      ]
    }
  ]
})
// 挂载路由导航守卫
router.beforeEach((to, form, next) => {
  // to代表要访问的页面
  // from 代表从那个页面来
  // next 放行函数
  // 1.如果访问的直接是登录页面,则直接放行
  if (to.path === '/login') return next()
  // 2.如果访问的是其他页面,则需要验证token
  const tokenStr = window.sessionStorage.getItem('token')
  // 2.1如果token验证不通过,则强制跳转到登录页面
  if (!tokenStr) return next('/login')
  // 2.2 如果token验证通过,则放行
  next()
})
export default router
